<?php
    include(dirname(__FILE__)."/../include/apility/apility.php");
    include(dirname(__FILE__)."/../Dao/db.php");
    include(dirname(__FILE__)."/../domain_url.php");

    class SynchronizeDownOne
    {
        //メンバID
        var $memberId;
        //アカント情報
        var $account;
        //情報設定
        var $authenticationContext;
        //例外の情報処理対象
        var $faultStack;

        var $domain_creative;
        var $domain_keyword;

        function SynchronizeDownOne($memberId)
        {
            //IDによって、アカント情報を取得
            $this->memberId = $memberId;
            $this->account = $this->getAccount($memberId);
            //例外処理対象を取得
            $this->faultStack = &APIlityFault::getFaultStack();
            //アカントの情報設定
            $this->authenticationContext = &APIlityAuthentication::getContext();

            $this->domain_creative = DOMAIN_URL."?Crt_Id=";
            $this->domain_keyword = DOMAIN_URL."?key_Id=";
        }

        function getAccount($memberId)
        {
            $allAccounts = array();
            $query = "SELECT * FROM account WHERE status=1 AND ";
            $query .= "memberId=$memberId";
            $result = mysql_query($query);
            if(!$result)
            {
                echo $query;
                echo "\r\n";
                echo mysql_errno() . ": " . mysql_error() . "\r\n";
            }
            else
            {
                if($row = mysql_fetch_array($result))
                {
                    return $row;
                }
            }
        }

        function Down()
        {
            echo date("Y-m-d H:i:s")."　Adwords→Adlistingバッチ（ユーザ別）開始\r\n\r\n";
            //アカント一つずつに処理する
            if(isset($this->account))
            {
                $accountName=$this->account['account_name'];
                $memberId=$this->account['memberId'];
                echo date("Y-m-d H:i:s")."　".$accountName."　開始\r\n";
                //GoogleAdwordsのロジック
                if($this->account['type'] == 1)
                {
                    echo "媒体種類：GoogleAdwords\r\n";
                    //クライアントアカント設定
                    if(!$this->setContext($accountName))
                    {
                        echo date("Y-m-d H:i:s")."　".$accountName."　終了\r\n\r\n";
                        return 3;
                    }

                    //キャンペーンを取得する
                    echo date("Y-m-d H:i:s")."　キャンペーンデータダウンロード開始\r\n";
                    $allCampaigns  = getAllCampaigns();
                    if(!is_array($allCampaigns))
                    {
                        echo date("Y-m-d H:i:s")."　キャンペーンデータを取得する時、エラーは発生しまいました";
                        $this->print_fault();
                        echo date("Y-m-d H:i:s")."　".$accountName."　終了\r\n\r\n";
                        return 3;
                    }
                    echo date("Y-m-d H:i:s")."　キャンペーンデータダウンロード完成\r\n";

                    //取得したキャンペーンによって、ローカルデータベースを更新する
                    echo date("Y-m-d H:i:s")."　ローカルデータベース更新開始\r\n";
                    //まず、ローカルDBに存在して、Adwords側に存在しないキャンペーンを削除（論理）
                    if(!$this->Delete_OldCampaign($allCampaigns,$memberId))
                    {
                        echo date("Y-m-d H:i:s")."　更新失敗しまいました\r\n";
                        return 3;
                    }
                    //存在しない場合、追加を行う。既に存在する場合、更新を行う
                    foreach($allCampaigns as $campaign)
                    {
                        $campaignId=$campaign->getId();
                        echo date("Y-m-d H:i:s")."　キャンペーンID：".$campaignId."\r\n";
                        $camp_Id = $this->UpdateCampaign($campaign,$memberId);
                        if(!$camp_Id)
                        {
                            echo date("Y-m-d H:i:s")."　更新失敗しまいました\r\n";
                            return 3;
                        }
                        else
                        {
                            echo date("Y-m-d H:i:s")."　更新成功しました\r\n";
                            echo date("Y-m-d H:i:s")."　広告グループ子項目をダウンロード開始\r\n";
                            $allAdGroups = getAllAdGroups($campaignId);
                            if(!is_array($allAdGroups))
                            {
                                echo date("Y-m-d H:i:s")."　広告グループを取得する時、エラーは発生しまいました";
                                $this->print_fault();
                                return 3;
                            }
                            echo date("Y-m-d H:i:s")."　広告グループデータダウンロード完成\r\n";

                            //取得した広告グループによって、ローカルデータベースを更新する
                            echo date("Y-m-d H:i:s")."　ローカルデータベース更新開始\r\n";
                            //まず、ローカルDBに存在して、Adwords側に存在しない広告グループを削除（論理）
                            if(!$this->Delete_OldAdGroup($allAdGroups,$memberId,$camp_Id))
                            {
                                echo date("Y-m-d H:i:s")."　更新失敗しまいました\r\n";
                                return 3;
                            }
                            ////存在しない場合、追加を行う。既に存在する場合、更新を行う
                            foreach($allAdGroups as $adGroup)
                            {
                                $adGroupId=$adGroup->getId();
                                echo date("Y-m-d H:i:s")."　広告グループID：".$adGroupId."\r\n";
                                $adGr_Id = $this->UpdateAdGroup($adGroup,$camp_Id,$memberId);
                                if(!$adGr_Id)
                                {
                                    echo date("Y-m-d H:i:s")."　更新失敗しまいました\r\n";
                                    return 3;
                                }

                                echo date("Y-m-d H:i:s")."　更新成功しました\r\n";
                                echo date("Y-m-d H:i:s")."　クリエイティブ子項目をダウンロード開始\r\n";
                                $allAds = getAllAds(array($adGroupId));
                                if(!is_array($allAds))
                                {
                                    echo date("Y-m-d H:i:s")."　クリエイティブを取得する時、エラーは発生しまいました";
                                    $this->print_fault();
                                    return 3;
                                }
                                else
                                {
                                    echo date("Y-m-d H:i:s")."　クリエイティブデータダウンロード完成\r\n";
                                    echo date("Y-m-d H:i:s")."　ローカルデータベース更新開始\r\n";
                                    //まず、ローカルDBに存在して、Adwords側に存在しないクリエイティブを削除（論理）
                                    if(!$this->Delete_OldAd($allAds,$memberId,$camp_Id,$adGr_Id))
                                    {
                                        echo date("Y-m-d H:i:s")."　更新失敗しまいました\r\n";
                                        return 3;
                                    }
                                    else
                                    {
                                        ////存在しない場合、追加を行う。既に存在する場合、更新を行う
                                        foreach($allAds as $ad)
                                        {
                                            $status = $ad->getStatus();
                                            //Disabledという意味はAdword側に削除された。だからローカルで管理必要ない
                                            if($status != "Disabled")
                                            {
                                                if(!$this->UpdateAd($ad,$adGr_Id,$camp_Id,$memberId))
                                                {
                                                    echo date("Y-m-d H:i:s")."　".$ad->getId()."更新失敗しまいました\r\n";
                                                    return 3;
                                                }
                                                else
                                                {
                                                    echo date("Y-m-d H:i:s")."　".$ad->getId()."更新成功しました\r\n";
                                                }
                                            }
                                        }
                                    }
                                }

                                echo date("Y-m-d H:i:s")."　キーワード子項目をダウンロード開始\r\n";
                                $allCriteria = getAllCriteria($adGroupId);
                                if(!is_array($allCriteria))
                                {
                                    echo date("Y-m-d H:i:s")."　キーワードを取得する時、エラーは発生しまいました";
                                    $this->print_fault();
                                    return 3;
                                }
                                else
                                {
                                    echo date("Y-m-d H:i:s")."　キーワードデータダウンロード完成\r\n";
                                    echo date("Y-m-d H:i:s")."　ローカルデータベース更新開始\r\n";
                                    //まず、ローカルDBに存在して、Adwords側に存在しないキーワードを削除（論理）
                                    if(!$this->Delete_OldKeyword($allCriteria,$memberId,$camp_Id,$adGr_Id))
                                    {
                                        echo date("Y-m-d H:i:s")."　更新失敗しまいました\r\n";
                                        return 3;
                                    }
                                    else
                                    {
                                        ////存在しない場合、追加を行う。既に存在する場合、更新を行う
                                        foreach($allCriteria as $keyword)
                                        {
                                            if(!$this->UpdateKeyword($keyword,$adGr_Id,$camp_Id,$memberId))
                                            {
                                                echo date("Y-m-d H:i:s")."　".$keyword->getId()."更新失敗しまいました\r\n";
                                                return 3;
                                            }
                                            else
                                            {
                                                echo date("Y-m-d H:i:s")."　".$keyword->getId()."更新成功しました\r\n";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                echo date("Y-m-d H:i:s")."　".$accountName."　終了\r\n\r\n";
            }
            else
            {
                echo date("Y-m-d H:i:s")."　id:".$this->memberId."のアカント情報を取得できません。\r\n";
                return 3;
            }
            echo date("Y-m-d H:i:s")."　Adwords→Adlistingバッチ（ユーザ別）終了\r\n";
            return 1;
        }

        //ウェブサービスをコール失敗場合、エラーメッセージを出力
        function print_fault()
        {
            $fault = array_pop($this->faultStack);
            if(isset($fault))
            {
                $fault->printFault();
            }
            else
            {
                echo "未知エラー。ネット接続問題かもしれません。\r\n";
            }
        }

        function setContext($ClientEmail)
        {
            //マネッジャのアカント設定
            $this->authenticationContext->setClientEmail($ClientEmail);
            if(!getAccountInfo())
            {
                $this->print_fault();
                echo date("Y-m-d H:i:s")."　該当クライアントアカントはクライアントセンターに管理しないかもしれません。或いはネット問題です。ご確認ください。\r\n";
                return false;
            }
            return true;
        }

        //ローカルDBに存在して、Adwords側に存在しないキャンペーンを削除（論理）
        //$allCampaigns：Adwords側に存在しているキャンペーン
        function Delete_OldCampaign($allCampaigns,$memberId)
        {
            $campaignIds = array();
            foreach($allCampaigns as $campaign)
            {
                array_push($campaignIds,$campaign->getId());
            }

            //ローカルDBにキャンペーンを検索
            $query = "SELECT  camp_Id,campaignId  FROM campaign WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "campaignId is not null AND ";
            $query .= "(status!=9 OR (status=9 AND sync=3)";

            $result = mysql_query($query);
            while($row = mysql_fetch_array($result))
            {
                $camp_Id = $row['camp_Id'];
                $campaignId=$row['campaignId'];
                //Adwords側に存在しない場合、削除を行う
                if(!in_array($campaignId,$campaignIds))
                {
                    $query = "UPDATE campaign SET ";
                    $query .= "status=9,sync=1,lastUpdate=now() WHERE ";
                    $query .= "memberId=$memberId AND ";
                    $query .= "listingType=1 AND ";
                    $query .= "campaignId=$campaignId";
                    if(!mysql_query($query))
                    {
                        echo $query;
                        echo "\r\n";
                        echo mysql_errno() . ": " . mysql_error() . "\r\n";
                        return false;
                    }
                    else
                    {
                        //該当キャンペーンの広告グループ、クリエイティブ、キーワード全部で削除
                        $query = "UPDATE adgroup SET status=9,sync=1,lastUpdate=now() ";
                        $query .= "WHERE camp_Id=$camp_Id";
                        mysql_query($query);

                        $query = "UPDATE creative SET status=9,sync=1,lastUpdate=now() ";
                        $query .= "WHERE camp_Id=$camp_Id";
                        mysql_query($query);

                        $query = "UPDATE keyword SET status=9,sync=1,lastUpdate=now() ";
                        $query .= "WHERE camp_Id=$camp_Id";
                        mysql_query($query);
                    }
                }
            }
            return true;
        }

        //$campaign：Adwordからのキャンペーン対象
        //ローカルデータベースに既に存在する場合、更新を行う。存在しない場合は挿入を行う。
        function updateCampaign($campaign,$memberId)
        {
            $campaignId=$campaign->getId();
            $name=$campaign->getName();
            $dailyBudget=$campaign->getBudgetAmount();
            $startDay=$campaign->getStartDate();
            $startDay=substr($startDay,0,10);
            $endDay=$campaign->getEndDate();
            $endDay=substr($endDay,0,10);
            //地域を取得して、「,」で分割する
            $geoTargeting_Obj=$campaign->getGeoTargets();
            $geoTargeting_array = $geoTargeting_Obj['countryTargets']['countries'];
            $geoTargeting = '';
            foreach($geoTargeting_array as $country)
            {
                $geoTargeting .= $country.",";
            }
            $geoTargeting = substr($geoTargeting,0,strlen($geoTargeting)-1);

            //言語を取得して、「,」で分割する
            $languageTargeting_array=$campaign->getLanguages();
            $languageTargeting = '';
            foreach($languageTargeting_array as $language)
            {
                $languageTargeting .= $language.",";
            }
            $languageTargeting = substr($languageTargeting,0,strlen($languageTargeting)-1);

            //ネットワークを取得して、「,」で分割する
            $networkTargeting_array=$campaign->getNetworkTargeting();
            $networkTargeting = '';
            foreach($networkTargeting_array as $network)
            {
                $networkTargeting .= $network.",";
            }
            $networkTargeting = substr($networkTargeting,0,strlen($networkTargeting)-1);

            //最適化設定を取得
            $enableBudgetOptimizer_Obj=$campaign->getBudgetOptimizerSettings();
            if($enableBudgetOptimizer_Obj['enabled'] == "true")
            {
                $enableBudgetOptimizer = 1;
            }
            else
            {
                $enableBudgetOptimizer = 0;
            }

            //
            $enableSeparateContentBids_bool=$campaign->getIsEnabledSeparateContentBids();
            if($enableSeparateContentBids_bool == "1")
            {
                $enableSeparateContentBids = 1;
            }
            else
            {
                $enableSeparateContentBids = 0;
            }

            //状態取得して、文字列から数字に変換する
            $status_str=$campaign->getStatus();
            $status = 0;
            if($status_str == "Paused")
            {
                $status = 0;
            }
            else
            {
                $status = 1;
            }
//            if($status_str == "Active")
//            {
//                $status = 1;
//            }
//            else if($status_str == "Paused")
//            {
//                $status = 0;
//            }
//            else if($status_str == "Pending")
//            {
//                $status = 2;
//            }
//            else if($status_str == "Suspended")
//            {
//                $status = 3;
//            }
//            else if($status_str == "Ended")
//            {
//                $status = 4;
//            }

            //該当キャンペーンはローカルDBに存在かどうか判断
            $query = "SELECT camp_Id FROM campaign WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "campaignId=$campaignId";

            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            //存在しない場合、挿入を行う
            if(!$row)
            {
                $query = "INSERT INTO campaign ( ";
                $query .= "memberId,listingType,campaignId,name,dailyBudget,";
                $query .= "startDay,endDay,geoTargeting,languageTargeting,networkTargeting,";
                $query .= "enableBudgetOptimizer,enableSeparateContentBids,status,sync,";
                $query .= "registDate,lastUpdate) VALUES ( ";
                $query .= "$memberId,";
                $query .= "1,";
                $query .= "$campaignId,";
                $query .= "'$name',";
                $query .= "$dailyBudget,";
                $query .= "'$startDay',";
                $query .= "'$endDay',";
                $query .= "'$geoTargeting',";
                $query .= "'$languageTargeting',";
                $query .= "'$networkTargeting',";
                $query .= "$enableBudgetOptimizer,";
                $query .= "$enableSeparateContentBids,";
                $query .= "$status,";
                $query .= "1,";
                $query .= "now(),now())";
                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
                else
                {
                    //挿入した後に$camp_Idを戻す
                    $query = "SELECT camp_Id FROM campaign WHERE ";
                    $query .= "memberId=$memberId AND ";
                    $query .= "listingType=1 AND ";
                    $query .= "campaignId=$campaignId AND ";
                    $query .= "status!=9";

                    $result = mysql_query($query);
                    $row = mysql_fetch_array($result);
                    if(!$row)
                    {
                        return false;
                    }
                    else
                    {
                        return $row['camp_Id'];
                    }
                }
            }
            //既に存在する場合、更新を行う
            else
            {
                $camp_Id = $row['camp_Id'];

                $query = "UPDATE campaign SET ";
                $query .= "name='$name',";
                $query .= "name='$name',";
                $query .= "dailyBudget=$dailyBudget,";
                $query .= "startDay='$startDay',";
                $query .= "endDay='$endDay',";
                $query .= "geoTargeting='$geoTargeting',";
                $query .= "languageTargeting='$languageTargeting',";
                $query .= "networkTargeting='$networkTargeting',";
                $query .= "enableBudgetOptimizer=$enableBudgetOptimizer,";
                $query .= "enableSeparateContentBids=$enableSeparateContentBids,";
                $query .= "status=$status,";
                $query .= "sync=1,";
                $query .= "lastUpdate=now() ";
                $query .= "WHERE camp_Id=$camp_Id ";
                $query .= "AND (sync=1 OR sync=3)";
                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
                else
                {
                    return $camp_Id;
                }
            }
        }

        //ローカルDBに存在して、Adwords側に存在しない広告グループを削除（論理）
        //$allAdGroups：Adwords側に存在している広告グループ
        function Delete_OldAdGroup($allAdGroups,$memberId,$camp_Id)
        {
            $addGroupIds = array();
            foreach($allAdGroups as $adGroup)
            {
                array_push($addGroupIds,$adGroup->getId());
            }

            //ローカルDBに広告グループを検索
            $query = "SELECT  adGr_Id,adGroupId  FROM adgroup WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "camp_Id=$camp_Id AND ";
            $query .= "adGroupId is not null AND ";
            $query .= "(status!=9 OR (status=9 AND sync=3)";

            $result = mysql_query($query);
            while($row = mysql_fetch_array($result))
            {
                $adGr_Id = $row['adGr_Id'];
                $adGroupId=$row['adGroupId'];
                //Adwords側に存在しない場合、削除を行う
                if(!in_array($adGroupId,$addGroupIds))
                {
                    $query = "UPDATE adgroup SET ";
                    $query .= "status=9,sync=1,lastUpdate=now() WHERE ";
                    $query .= "memberId=$memberId AND ";
                    $query .= "listingType=1 AND ";
                    $query .= "camp_Id=$camp_Id AND ";
                    $query .= "adGroupId=$adGroupId";
                    if(!mysql_query($query))
                    {
                        echo $query;
                        echo "\r\n";
                        echo mysql_errno() . ": " . mysql_error() . "\r\n";
                        return false;
                    }
                    else
                    {
                        $query = "UPDATE creative SET status=9,sync=1,lastUpdate=now() ";
                        $query .= "WHERE adGr_Id=$adGr_Id";
                        mysql_query($query);

                        $query = "UPDATE keyword SET status=9,sync=1,lastUpdate=now() ";
                        $query .= "WHERE adGr_Id=$adGr_Id";
                        mysql_query($query);
                    }
                }
            }
            return true;
        }

        function UpdateAdGroup($adGroup,$camp_Id,$memberId)
        {
            $adGroupId=$adGroup->getId();
            $maxContentCpc=$adGroup->getKeywordContentMaxCpc();
            if(!isset($maxContentCpc))
            {
                $maxContentCpc = 0;
            }
            $maxCpc=$adGroup->getKeywordMaxCpc();
            if(!isset($maxCpc))
            {
                $maxCpc = 0;
            }
            $maxCpm=$adGroup->getSiteMaxCpm();
            if(!isset($maxCpm))
            {
                $maxCpm = 0;
            }
            $name=$adGroup->getName();
            //$landingURL,countType?????
            $status_str=$adGroup->getStatus();
            $status = 0;
            if($status_str == "Active")
            {
                $status = 1;
            }
            else if($status_str == "Paused")
            {
                $status = 0;
            }

            //該当広告グループはローカルDBに存在かどうかのチェック
            $query = "SELECT adGr_Id FROM adgroup WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "camp_Id=$camp_Id AND ";
            $query .= "adGroupId=$adGroupId";

            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            //ローカルデータベースに存在しない場合、挿入操作を行う
            if(!$row)
            {
                $query = "INSERT INTO adgroup ( ";
                $query .= "memberId,listingType,camp_Id,adGroupId,";
                $query .= "maxContentCpc,maxCpc,maxCpm,";
                $query .= "name,status,sync,registDate,lastUpdate ) VALUES ( ";
                $query .= "$memberId,";
                $query .= "1,";
                $query .= "$camp_Id,";
                $query .= "$adGroupId,";
                $query .= "$maxContentCpc,";
                $query .= "$maxCpc,";
                $query .= "$maxCpm,";
                $query .= "'$name',";
                $query .= "$status,";
                $query .= "1,now(),now())";

                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
                else
                {
                    //挿入した後に$adGr_Idを戻す
                    $query = "SELECT adGr_Id FROM adgroup WHERE ";
                    $query .= "memberId=$memberId AND ";
                    $query .= "listingType=1 AND ";
                    $query .= "camp_Id=$camp_Id AND ";
                    $query .= "adGroupId=$adGroupId AND ";
                    $query .= "status!=9";

                    $result = mysql_query($query);
                    $row = mysql_fetch_array($result);
                    if(!$row)
                    {
                        return false;
                    }
                    else
                    {
                        return $row['adGr_Id'];
                    }
                }
            }
            else
            {
                $adGr_Id = $row['adGr_Id'];

                $query = "UPDATE adgroup SET ";
                $query .= "maxContentCpc=$maxContentCpc,";
                $query .= "maxCpc=$maxCpc,";
                $query .= "maxCpm=$maxCpm,";
                $query .= "name='$name',";
                $query .= "status=$status,";
                $query .= "sync=1,";
                $query .= "lastUpdate=now() ";
                $query .= "WHERE adGr_Id=$adGr_Id ";
                $query .= "AND (sync=1 OR sync=3)";

                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
                else
                {
                    return $adGr_Id;
                }
            }
        }

        //ローカルDBに存在して、Adwords側に存在しないクリエイティブを削除（論理）
        //$allAds：Adwords側に存在しているクリエイティブ
        function Delete_OldAd($allAds,$memberId,$camp_Id,$adGr_Id)
        {
            $creativeIds = array();
            foreach($allAds as $ad)
            {
                if($ad->getStatus() != "Disabled")
                {
                    array_push($creativeIds,$ad->getId());
                }
            }

            //ローカルDBにクリエイティブを検索
            $query = "SELECT  creativeId  FROM creative WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "camp_Id=$camp_Id AND ";
            $query .= "adGr_Id=$adGr_Id AND ";
            $query .= "creativeId is not null AND ";
            $query .= "(status!=9 OR (status=9 AND sync=3)";

            $result = mysql_query($query);
            while($row = mysql_fetch_array($result))
            {
                $creativeId=$row['creativeId'];
                //Adwords側に存在しない場合、削除を行う
                if(!in_array($creativeId,$creativeIds))
                {
                    $query = "UPDATE creative SET ";
                    $query .= "status=9,sync=1,lastUpdate=now() WHERE ";
                    $query .= "memberId=$memberId AND ";
                    $query .= "listingType=1 AND ";
                    $query .= "camp_Id=$camp_Id AND ";
                    $query .= "adGr_Id=$adGr_Id AND ";
                    $query .= "creativeId=$creativeId";
                    if(!mysql_query($query))
                    {
                        echo $query;
                        echo "\r\n";
                        echo mysql_errno() . ": " . mysql_error() . "\r\n";
                        return false;
                    }
                }
            }
            return true;
        }

        function UpdateAd($ad,$adGr_Id,$camp_Id,$memberId)
        {
            $creativeId=$ad->getId();
//            $name=$ad->getName();    No this method
            $description1=$ad->getDescription1();
            $description2=$ad->getDescription2();
            $destinationUrl=$ad->getDestinationUrl();

            $displayUrl=$ad->getDisplayUrl();
            $headline=$ad->getHeadline();
            $status_str=$ad->getStatus();
            $status = 0;
            if($status_str == "Enabled")
            {
                $status = 1;
            }
            else if($status_str == "Paused")
            {
                $status = 0;
            }

            $query = "SELECT Crt_Id FROM creative WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "camp_Id=$camp_Id AND ";
            $query .= "adGr_Id=$adGr_Id AND ";
            $query .= "creativeId=$creativeId";

            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            //ローカルデータベースに存在しない場合、挿入を行う
            if(!$row)
            {
                $query = "INSERT INTO creative ( ";
                $query .= "memberId,listingType,camp_Id,adGr_Id,creativeId,";
                $query .= "description1,description2,";
                $query .= "destinationUrl,redirectUrl,displayUrl,headline,";
                $query .= "status,sync,registDate,lastUpdate ) VALUES ( ";
                $query .= "$memberId,";
                $query .= "1,";
                $query .= "$camp_Id,";
                $query .= "$adGr_Id,";
                $query .= "$creativeId,";
                $query .= "'$description1',";
                $query .= "'$description2',";
                $query .= "CASE WHEN INSTR('$destinationUrl','$this->domain_creative') THEN '' ELSE '$destinationUrl' END,";
                $query .= "CASE WHEN INSTR('$destinationUrl','$this->domain_creative') THEN '$destinationUrl' ELSE '' END,";
                $query .= "'$displayUrl',";
                $query .= "'$headline',";
                $query .= "$status,";
                $query .= "1,now(),now())";
                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
                else
                {
                    $query = "UPDATE  creative SET ";
                    $query .= "redirectUrl=CONCAT('$this->domain_creative',Crt_Id) ";
                    $query .= "WHERE  adGr_Id=$adGr_Id ";
                    $query .= "AND    creativeId=$creativeId";
                    if(!mysql_query($query))
                    {
                        echo $query;
                        echo "\r\n";
                        echo mysql_errno() . ": " . mysql_error() . "\r\n";
                        return false;
                    }
                }
            }
            //既に存在する場合、更新を行う
            else
            {
                $Crt_Id = $row['Crt_Id'];

                $query = "UPDATE creative SET ";
                $query .= "description1='$description1',";
                $query .= "description2='$description2',";
                $query .= "destinationUrl=CASE WHEN INSTR('$destinationUrl','$this->domain_creative') THEN destinationUrl ELSE '$destinationUrl' END,";
                $query .= "redirectUrl=CASE WHEN INSTR('$destinationUrl','$this->domain_creative') THEN '$destinationUrl' ELSE CONCAT('$this->domain_creative',Crt_Id) END,";
                $query .= "displayUrl='$displayUrl',";
                $query .= "headline='$headline',";
                $query .= "status=$status,";
                $query .= "sync=1,";
                $query .= "lastUpdate=now() WHERE ";
                $query .= "Crt_Id=$Crt_Id ";
                $query .= "AND (sync=1 OR sync=3)";
                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
            }

            if(strpos($destinationUrl,$this->domain_creative) === False)
            {
                $query = "SELECT  redirectUrl ";
                $query .= "FROM   creative ";
                $query .= "WHERE  adGr_Id=$adGr_Id ";
                $query .= "AND    creativeId=$creativeId ";
                $result = mysql_query($query);
                $row = mysql_fetch_array($result);

                if(!$ad->setDestinationUrl($row['redirectUrl']))
                {
                    $fault = array_pop($this->faultStack);
                    if(isset($fault))
                    {
                        $fault->printFault();
                    }
                    return false;
                }
            }
            return true;
        }

        //ローカルDBに存在して、Adwords側に存在しないキーワードを削除（論理）
        //$allKeywords：Adwords側に存在しているキーワード
        function Delete_OldKeyword($allKeywords,$memberId,$camp_Id,$adGr_Id)
        {
            $keywordIds = array();
            foreach($allKeywords as $keyword)
            {
                array_push($keywordIds,$keyword->getId());
            }

            //ローカルDBにキーワードを検索
            $query = "SELECT  keywordId  FROM keyword WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "camp_Id=$camp_Id AND ";
            $query .= "adGr_Id=$adGr_Id AND ";
            $query .= "keywordId is not null AND ";
            $query .= "(status!=9 OR (status=9 AND sync=3)";

            $result = mysql_query($query);
            while($row = mysql_fetch_array($result))
            {
                $keywordId=$row['keywordId'];
                //Adwords側に存在しない場合、削除を行う
                if(!in_array($keywordId,$keywordIds))
                {
                    $query = "UPDATE keyword SET ";
                    $query .= "status=9,sync=1,lastUpdate=now() WHERE ";
                    $query .= "memberId=$memberId AND ";
                    $query .= "listingType=1 AND ";
                    $query .= "camp_Id=$camp_Id AND ";
                    $query .= "adGr_Id=$adGr_Id AND ";
                    $query .= "keywordId=$keywordId";
                    if(!mysql_query($query))
                    {
                        echo $query;
                        echo "\r\n";
                        echo mysql_errno() . ": " . mysql_error() . "\r\n";
                        return false;
                    }
                }
            }
            return true;
        }

        function UpdateKeyword($keyword,$adGr_Id,$camp_Id,$memberId)
        {
            $keywordId=$keyword->getId();
            $destinationUrl=$keyword->getDestinationUrl();
            $maxCpc=$keyword->getMaxCpc();
            $negative=$keyword->getIsNegative();
            $paused_bool=$keyword->getIsPaused();
            $paused = 1;
            if($paused_bool)
            {
                $paused = 1;
            }
            else
            {
                $paused = 0;
            }
            $status_str=$keyword->getStatus();
            $status = 0;
            if($status_str == "Active")
            {
                $status = 1;
            }
            else if($status_str == "Disapproved")
            {
                $status = 2;
            }
            $text=$keyword->getText();
            $type_str=$keyword->getType();
            $type = 2;
            if($type_str == "Exact")
            {
                $type = 1;
            }
            else
            {
                $type = 2;
            }

            $query = "SELECT key_Id FROM keyword WHERE ";
            $query .= "memberId=$memberId AND ";
            $query .= "listingType=1 AND ";
            $query .= "camp_Id=$camp_Id AND ";
            $query .= "adGr_Id=$adGr_Id AND ";
            $query .= "keywordId=$keywordId";

            $result = mysql_query($query);
            $row = mysql_fetch_array($result);
            //ローカルデータベースに存在しない場合、挿入を行う
            if(!$row)
            {
                $query = "INSERT INTO keyword ( ";
                $query .= "memberId,listingType,camp_Id,adGr_Id,keywordId,";
                $query .= "destinationUrl,redirectUrl,maxCpc,negative,";
                $query .= "paused,status,text,type,";
                $query .= "sync,registDate,lastUpdate) VALUES ( ";
                $query .= "$memberId,";
                $query .= "1,";
                $query .= "$camp_Id,";
                $query .= "$adGr_Id,";
                $query .= "$keywordId,";
                $query .= "CASE WHEN INSTR('$destinationUrl','$this->domain_keyword') THEN '' ELSE '$destinationUrl' END,";
                $query .= "CASE WHEN INSTR('$destinationUrl','$this->domain_keyword') THEN '$destinationUrl' ELSE '' END,";
                $query .= "$maxCpc,";
                $query .= "$negative,";
                $query .= "$paused,";
                $query .= "$status,";
                $query .= "'$text',";
                $query .= "$type,";
                $query .= "1,now(),now())";
                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
                else
                {
                    $query = "UPDATE  keyword SET ";
                    $query .= "redirectUrl=CONCAT('$this->domain_keyword',key_Id) ";
                    $query .= "WHERE  adGr_Id=$adGr_Id ";
                    $query .= "AND    keywordId=$keywordId";
                    if(!mysql_query($query))
                    {
                        echo $query;
                        echo "\r\n";
                        echo mysql_errno() . ": " . mysql_error() . "\r\n";
                        return false;
                    }
                }
            }
            //既に存在する場合、更新を行う
            else
            {
                $key_Id = $row['key_Id'];

                $query = "UPDATE keyword SET ";
                $query .= "destinationUrl=CASE WHEN INSTR('$destinationUrl','$this->domain_keyword') THEN destinationUrl ELSE '$destinationUrl' END,";
                $query .= "redirectUrl=CASE WHEN INSTR('$destinationUrl','$this->domain_keyword') THEN '$destinationUrl' ELSE CONCAT('$this->domain_keyword',key_Id) END,";
                $query .= "maxCpc=$maxCpc,";
                $query .= "negative=$negative,";
                $query .= "paused=$paused,";
                $query .= "status=$status,";
                $query .= "text='$text',";
                $query .= "type=$type,";
                $query .= "sync=1,";
                $query .= "lastUpdate=now() WHERE ";
                $query .= "key_Id=$key_Id ";
                $query .= "AND (sync=1 OR sync=3)";
                if(!mysql_query($query))
                {
                    echo $query;
                    echo "\r\n";
                    echo mysql_errno() . ": " . mysql_error() . "\r\n";
                    return false;
                }
            }

            if(strpos($destinationUrl,$this->domain_keyword) === False)
            {
                $query = "SELECT  redirectUrl ";
                $query .= "FROM   keyword ";
                $query .= "WHERE  adGr_Id=$adGr_Id ";
                $query .= "AND    keywordId=$keywordId ";
                $result = mysql_query($query);
                $row = mysql_fetch_array($result);

                if(!$keyword->setDestinationUrl($row['redirectUrl']))
                {
                    $fault = array_pop($this->faultStack);
                    if(isset($fault))
                    {
                        $fault->printFault();
                    }
                    return false;
                }
            }
            return true;
        }
    }
?>
